package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.context.ApiContext;
import com.xmy.cultivate.entity.AuthAdminContent;
import com.xmy.cultivate.entity.response.AllotDataRs;
import com.xmy.cultivate.entity.views.FenAdminData;
import com.xmy.cultivate.entity.views.LeadDataRs;
import com.xmy.cultivate.mapper.AuthAdminContentMapper;
import com.xmy.cultivate.service.IAuthAdminContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.service.ISchoolQuarterService;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.DateUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 内容【数据】权限 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-04-26
 */
@Service
public class AuthAdminContentServiceImpl extends ServiceImpl<AuthAdminContentMapper, AuthAdminContent> implements IAuthAdminContentService {

    @Autowired
    AuthAdminContentMapper authAdminContentMapper;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Override
    public AuthAdminContent getPermissionForTeacherId(Integer yearPart, Integer quarterNum, Long teacherId, String baseSchoolIdStr){
        String methAlias = "";
        AllotDataRs allotDataRs = new AllotDataRs();
        try {
            methAlias = ApiContext.getMethodAlias();
            if (!StringUtils.isEmpty(methAlias)){
                List<String> methAliasList = Arrays.asList(methAlias.split(","));
                String methAliasStr = methAliasList.stream()
                        .map(element -> "'" + element + "'")  // 为每个元素添加单引号
                        .collect(Collectors.joining(", "));
                allotDataRs =  this.getAllotData(teacherId,methAliasStr);
            }
        }finally {
            ApiContext.clear();
        }
        //System.out.println("methAlias:"+methAlias);


        AuthAdminContent authAdminContent;
        LeadDataRs leadDataRs = this.getLeadData(yearPart,quarterNum,teacherId);
        if (teacherId.equals(1568138350324350975L)){
            String schoolStr = iSchoolQuarterService.getSchoolIdStr(yearPart,quarterNum);
            authAdminContent = new AuthAdminContent();
            authAdminContent.setIsAdmin(1);
            authAdminContent.setSchoolIds(schoolStr);
            authAdminContent.setSubjectsIds("1,2,3");
            authAdminContent.setYearClassIds("0,1,2,3,4,5,6,7,8,9,10,11,12");
        }else {
            //是否是负责人
            QueryWrapper<AuthAdminContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("teacher_id",teacherId);
            queryWrapper.last("limit 1");
            authAdminContent = authAdminContentMapper.selectOne(queryWrapper);
            if(ObjectUtils.isNull(authAdminContent)){
                //个人
                authAdminContent = new AuthAdminContent();
                if (!Objects.isNull(allotDataRs)){
                    if(StringUtils.isNotBlank(allotDataRs.getSchoolIds())){
                        authAdminContent.setIsPerson(0);
                    }else {
                        authAdminContent.setIsPerson(1);
                    }
                }else {
                    authAdminContent.setIsPerson(1);
                }

                //获取带班数据
                //authAdminContent.setSchoolIds(leadDataRs.getSchoolIds());
                //authAdminContent.setYearClassIds(leadDataRs.getYearClassIds());
                //authAdminContent.setSubjectsIds(leadDataRs.getSubjectsIds());
                authAdminContent.setSchoolIds("-1");
                authAdminContent.setYearClassIds("-1");
                authAdminContent.setSubjectsIds("-1");
            }else {
                //张康成、陆圭容、李紫娟、陈佳、郑敏、王常斐可查看所有校区
                Long[] superTeacher = {1606827870716428288L,1600467041876180992L,1600478600534949888L,1600474023119028224L,1600482952192458752L,1600485806412136448L};
                boolean existsTeacher = Arrays.asList(superTeacher).contains(teacherId);
                if (existsTeacher){
                    String schoolStr = iSchoolQuarterService.getSchoolIdStr(yearPart,quarterNum);
                    authAdminContent.setSchoolIds(schoolStr);
                }else {
                    if (authAdminContent.getSchoolIds() == null){
                        authAdminContent.setSchoolIds("-1");
                    }
                }
                if (authAdminContent.getSubjectsIds() == null){
                    authAdminContent.setSubjectsIds("-1");
                }
                if (authAdminContent.getYearClassIds() == null){
                    authAdminContent.setYearClassIds("-1");
                }
                authAdminContent.setIsPerson(0);
            }
            authAdminContent.setIsAdmin(0);
        }


        authAdminContent.setTeacherId(teacherId);
        authAdminContent.setLeadDataRs(leadDataRs);
        //获取科目并集
        String combineSubjects = CommonUtil.getStrUnion(authAdminContent.getSubjectsIds().replace("-1",""),leadDataRs.getSubjectsIds().replace("-1",""));;
        authAdminContent.setCombineSubjectsIds(combineSubjects);

        //合并分享的权限
        if (StringUtils.isNotBlank(allotDataRs.getSchoolIds())){
            authAdminContent.setSchoolIds(CommonUtil.getStrUnion(authAdminContent.getSchoolIds(),allotDataRs.getSchoolIds()));
        }
        if (StringUtils.isNotBlank(allotDataRs.getSubjectsIds())){
            authAdminContent.setSubjectsIds(CommonUtil.getStrUnion(authAdminContent.getSubjectsIds(),allotDataRs.getSubjectsIds()));
        }
        if (StringUtils.isNotBlank(allotDataRs.getYearClassIds())){
            authAdminContent.setYearClassIds(CommonUtil.getStrUnion(authAdminContent.getYearClassIds(),allotDataRs.getYearClassIds()));
        }

        if (StringUtils.isNotBlank(authAdminContent.getSchoolIds())){
            String[] stringArray = authAdminContent.getSchoolIds().split(",");
            List<Long> integerList = new ArrayList<>();
            for (String str : stringArray) {
                Long number = Long.parseLong(str);
                integerList.add(number);
            }
            authAdminContent.setSchoolIdList(integerList);
        }

        return authAdminContent;
    }


    private LeadDataRs getLeadData(Integer yearPart, Integer quarterNum, Long teacherId) {
        LeadDataRs leadDataRs = authAdminContentMapper.getLeadData(yearPart,quarterNum,teacherId);
        if (Objects.isNull(leadDataRs)){
            leadDataRs = new LeadDataRs();
            leadDataRs.setSchoolIds("-1");
            leadDataRs.setSubjectsIds("-1");
            leadDataRs.setYearClassIds("-1");
        }
        if (StringUtils.isNotBlank(leadDataRs.getSchoolIds())){
            String[] stringArray = leadDataRs.getSchoolIds().split(",");
            List<Long> integerList = new ArrayList<>();
            for (String str : stringArray) {
                Long number = Long.parseLong(str);
                integerList.add(number);
            }
            leadDataRs.setSchoolIdList(integerList);
        }
        leadDataRs.setTeacherId(teacherId);
        return leadDataRs;
    }


    //Ifein调用获取Admin值
    @Override
    public FenAdminData getAdminData(Integer yearPart,Integer quarterNum){
        FenAdminData fenAdminData = new FenAdminData();
        fenAdminData.setAdminId(1568138350324350975L);
        List<Long> schoolIdList = iSchoolQuarterService.getSchoolIdList(yearPart,quarterNum);
        fenAdminData.setBaseSchoolIdList(schoolIdList);
        String schoolIdStr = CommonUtil.listLongToStr(schoolIdList);
        fenAdminData.setBaseSchoolIdStr(schoolIdStr);
        return fenAdminData;
    }

    @Override
    public String getIntersectionForStr(String str1, String str2){
        str1 = str1.replace("-1","");
        str2 = str2.replace("-1","");
        String str = CommonUtil.getStrIntersection(str1,str2);
        if (StringUtils.isBlank(str)){
            str = "-1";
        }
        return str;
    }

    /**
     *
     * @param teacherId
     * @param projectName 项目名称
     * @return
     */
    public AllotDataRs getAllotData(Long teacherId,
                                    String projectName){
        Integer weeksIndex = DateUtil.getWeekIndex(LocalDate.now());//获取当前星期几
        // 获取当前时间
        //LocalTime now = LocalTime.now();
        // 定义日期时间格式化器
        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        // 格式化时间
        //String nowTime = now.format(formatter);
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);


        AllotDataRs allotDataRs = null;
        List<AllotDataRs> allotDataRsList = authAdminContentMapper.getAllotData(teacherId,weeksIndex,localDateTime.toString(),projectName);
        for (AllotDataRs allotDataRsInfo : allotDataRsList){
            allotDataRs = allotDataRsInfo;
        }
        if (Objects.isNull(allotDataRs)){
            allotDataRs = new AllotDataRs();
        }
        return allotDataRs;
    }

    @Override
    public List<String> getAllotCode(@Param("teacherId") Long teacherId){
        Integer weeksIndex = DateUtil.getWeekIndex(LocalDate.now());//获取当前星期几
        // 获取当前时间
        LocalTime now = LocalTime.now();
        // 定义日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

        // 格式化时间
        String nowTime = now.format(formatter);
        List<String> stringList = authAdminContentMapper.getAllotCode(teacherId,weeksIndex,nowTime);
        return stringList;
    }
}
